package top.yuhaitao.core.controller;

import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yuhaitao.core.controller.RequestModel.RequestTest;
import top.yuhaitao.core.service.SecondKillSevice;
import top.yuhaitao.core.util.WechatUtil;
import top.yuhaitao.core.util.XMLUtil;
import top.yuhaitao.core.wechat.Constant;
import top.yuhaitao.core.wechat.MessageUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * index
 *
 * @author ht.yu 75751845@qq.com
 * @date 2019-1-25 18:45:03
 */

@RestController
public class IndexController {

    private Logger log = LoggerFactory.getLogger(IndexController.class);

    private final static String dev = "gh_ab122d3f7a4d";
    private final static String appid = "wxdeb6767d0c011d8d";
    private final static String secret = "9a98e1ad6586689c9925401f1f1f337f";

    private final static String WECHAT_HEALCHECK_TOKEN = "wechat_token";
    private final static String ENCODING_AES_KEY = "N8JKTf4n6qIxYLPl2Xcqb5KH96tPUXQXtjXG6NYrXri";

    @Resource
    private SecondKillSevice secondKillSevice;

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/test")
    public RequestTest test(String namename, String sexsex, @RequestBody RequestTest request) {
        System.out.println("request : " + request);
        System.out.println("namename : " + namename);
        System.out.println("sexsex : " + sexsex);
        return request;
    }

    /**
     * 微信服务器认证
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     */
//    @RequestMapping("/healcheck")
    public String healcheck(String signature, String timestamp, String nonce, String echostr) {
        if (StringUtils.isEmpty(timestamp) || StringUtils.isEmpty(nonce) || StringUtils.isEmpty(echostr) || StringUtils.isEmpty(signature)) {
            return null;
        }
        if (WechatUtil.validateSignature(WECHAT_HEALCHECK_TOKEN, nonce, timestamp, signature)) {
            return echostr;
        }
        return null;
    }


    /**
     * 微信推送的消息
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     */
    @RequestMapping("/healcheck")
    public String healcheck(String signature, String timestamp, String nonce, String echostr, @RequestBody byte[] bytes) {
        log.info("signature : " + signature + ",timestamp : " + timestamp + " ,nonce : " + nonce + " ,echostr : " + echostr);
        String postBody = new String(bytes, StandardCharsets.UTF_8);
        log.info("postBody : " + postBody);
        //验签
        if (!WechatUtil.validateSignature(WECHAT_HEALCHECK_TOKEN, nonce, timestamp, signature)) {
            return null;
        }
        Document document = XMLUtil.readString2XML(postBody);
        Element root = document.getRootElement();
        String MsgType = XMLUtil.readNode(root, Constant.MsgType);
        String user = XMLUtil.readNode(root, Constant.FromUserName);
        String dev = XMLUtil.readNode(root, Constant.ToUserName);

        // 文本
        if ("text".equals(MsgType)) {
            return MessageUtil.replyMessage(dev, user, "自动回复");
        }

        // 关注事件
        if ("event".equals(MsgType)) {
            String subscribe = XMLUtil.readNode(root, "Event");
            if ("subscribe".equals(subscribe)) {
                return MessageUtil.replyMessage(dev, user, "关注事件");
            } else {
                return MessageUtil.replyMessage(dev, user, "取笑关注事件");
            }
        }

        // 扫码事件

        return postBody;
    }

    @RequestMapping("/getAccesstoken")
    public String getAccessToken() throws IOException {
        String accesstoken = WechatUtil.getAccesstoken();
        log.info("accesstoken : " + accesstoken);
        return accesstoken;
    }

    @RequestMapping("/createQrcode")
    public String createQrcode(String accesstoken) throws IOException {
        String qrcode = WechatUtil.createQrcode(accesstoken);
        log.info("qrcode : " + qrcode);
        return qrcode;
    }

    public static void main(String[] args) {
        String postBody = "<xml><ToUserName><![CDATA[gh_ab122d3f7a4d]]></ToUserName>\n" +
                "<FromUserName><![CDATA[ouF-_wRMe8HXVeaL_aE4ikpPGpN4]]></FromUserName>\n" +
                "<CreateTime>1548439125</CreateTime>\n" +
                "<MsgType><![CDATA[text]]></MsgType>\n" +
                "<Content><![CDATA[你好啊]]></Content>\n" +
                "<MsgId>6650495402188132778</MsgId>\n" +
                "</xml>";
        String s = MessageUtil.replyMessage("dev", "user", "msg");
        System.out.println(s);
    }
}
